package org.yan.kangaroo.auth.config.security.provider;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.yan.kangaroo.auth.config.security.SecurityUserDetails;
import org.yan.kangaroo.auth.service.UserAuthService;
import org.yan.kangaroo.auth.service.UserService;
import org.yan.kangaroo.pojo.ucenter.entity.User;
import org.yan.kangaroo.pojo.ucenter.entity.UserAuth;

/**
 * @author wangx
 * @date 11/13/2019 11:08
 */
@Component
@Slf4j
@AllArgsConstructor
public class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {
    private final UserAuthService userAuthService;

    private final UserService userService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();
        UserAuth userAuth = userAuthService.findByIdentifier(username);
        if (userAuth == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if (!new BCryptPasswordEncoder().matches(password, userAuth.getCredential())) {
            throw new BadCredentialsException("用户名或密码错误");

        }
        User user = userService.findByAccountId(userAuth.getAccountId());
        SecurityUserDetails userDetails = new SecurityUserDetails(user, username, userAuth.getCredential());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, "", null);
        log.info("[authenticate] token:{}", usernamePasswordAuthenticationToken);
        return usernamePasswordAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
